<template>
  <div class="exercise-detail">
    <el-card class="exercise-card" v-loading="loading">
      <!-- 头部区域 -->
      <template #header>
        <ExerciseHeader 
          :title="exerciseSet.title" 
          :is-public="exerciseSet.is_public" 
          :has-exercises="exercises.length > 0"
          :is-completed="progress && progress.is_completed"
          @go-back="goBack"
          @start-exercise="startExercise"
        />
      </template>

      <!-- Debug info -->
      <div class="debug-info" style="margin-bottom: 10px; color: #999; font-size: 12px;">
        Debug: isExercising = {{ isExercising }}, exercises.length = {{ exercises.length }}
      </div>
      
      <!-- 练习集信息和进度 -->
      <ExerciseOverview 
        v-if="exerciseSet.id && !isExercising"
        :exercise-set="exerciseSet"
        :exercises="exercises"
        :progress="progress"
        @reset-progress="resetProgress"
      />

      <!-- 练习模式 - 使用新的ExercisePractice组件 -->
      <ExercisePractice
        v-if="isExercising"
        :questions="exercises"
        :timer-enabled="true"
        :show-feedback-immediately="true"
        @submit-answer="handleSubmitAnswer"
        @finish-practice="handleFinishPractice"
        @update-progress="handleUpdateProgress"
      />

      <!-- 题目列表 -->
      <ExerciseQuestionList
        v-if="!isExercising && exercises.length > 0"
        :questions="exercises"
        :progress="progress"
        :selected-question-id="selectedQuestionId"
        @select-question="handleSelectQuestion"
        @start-practice="handleStartPractice"
      />

      <el-empty v-if="!loading && !exerciseSet.id" description="未找到练习集" :image-size="200">
        <el-button type="primary" @click="goBack">返回列表</el-button>
      </el-empty>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Back, Reading } from '@element-plus/icons-vue'
import http from '../utils/axios'  // 使用配置好的axios实例
import ExerciseHeader from './exercise/ExerciseHeader.vue'
import ExerciseOverview from './exercise/ExerciseOverview.vue'
import ExercisePractice from './exercise/ExercisePractice.vue'
import ExerciseQuestionList from './exercise/ExerciseQuestionList.vue'

const router = useRouter()
const route = useRoute()
const props = defineProps({
  id: {
    type: [String, Number],
    required: true
  }
})

// 状态变量
const loading = ref(false)
const exerciseSet = ref({})
const exercises = ref([])
const progress = ref(null)
const records = ref([])
const isExercising = ref(false)
const currentQuestionIndex = ref(0)
const userAnswer = ref('')
const showAnswer = ref(false)
const markedQuestions = ref(new Set())
const elapsedTime = ref(0)
const isTimerRunning = ref(false)
const timerInterval = ref(null)
const filteredQuestions = ref([])
const activeFilter = ref('all')
const selectedQuestionId = ref(null)

// 获取练习集详情
const fetchExerciseSet = async () => {
  loading.value = true
  try {
    // 检查是否有有效的练习集ID
    if (!props.id || props.id === 'undefined' || props.id === 'my-exercises' || props.id === 'recent' || props.id === 'statistics' || props.id === 'create') {
      console.error('练习集ID无效:', props.id)
      ElMessage.error('练习集ID无效，无法获取练习集详情')
      loading.value = false
      
      // 如果是静态路由被误解析为ID，重定向到正确的路由
      if (['my-exercises', 'recent', 'statistics', 'create'].includes(props.id)) {
        router.replace(`/dashboard/exercises/${props.id}`)
      } else {
        router.replace('/dashboard/exercises')
      }
      return
    }
    
    const response = await http.get(`/exercises/exercise-sets/${props.id}/`)
    exerciseSet.value = response.data
    
    // 统一使用exercises数组
    if (response.data.exercises && Array.isArray(response.data.exercises)) {
      exercises.value = response.data.exercises
    } else if (response.data.questions && Array.isArray(response.data.questions)) {
      exercises.value = response.data.questions
    } else {
      exercises.value = []
    }
    
    await fetchProgress()
    await fetchRecords()
    
    // 如果有题目，设置当前题目为第一题
    if (exercises.value.length > 0) {
      currentQuestionIndex.value = 0
    }
  } catch (error) {
    console.error('获取练习集详情失败:', error)
    ElMessage.error('获取练习集详情失败')
    
    // 如果是404错误，可能是ID无效，重定向到练习集列表
    if (error.response && error.response.status === 404) {
      router.replace('/dashboard/exercises')
    }
  } finally {
    loading.value = false
  }
}

// 获取练习进度
const fetchProgress = async () => {
  // 检查是否有有效的练习集ID
  if (!props.id) {
    console.warn('练习集ID无效，无法获取练习进度')
    progress.value = null
    return
  }
  
  // 检查是否有有效的用户ID
  const userId = localStorage.getItem('user_id')
  if (!userId) {
    console.warn('用户ID无效，无法获取练习进度')
    progress.value = null
    return
  }
  
  try {
    // 使用正确的API端点
    const response = await http.get(`/exercises/progress/current/`)
    
    // 如果返回的是数组，查找匹配的进度
    if (Array.isArray(response.data) && response.data.length > 0) {
      // 查找与当前练习集ID匹配的进度
      const matchingProgress = response.data.find(p => p.exercise_set == props.id)
      progress.value = matchingProgress || null
      
      if (matchingProgress) {
        console.log('找到练习进度:', matchingProgress)
      } else {
        console.log('未找到练习进度，可能是首次练习')
      }
    } else {
      progress.value = null
      console.log('未找到任何练习进度')
    }
  } catch (error) {
    console.error('获取练习进度失败:', error)
    progress.value = null
  }
}

// 获取练习记录
const fetchRecords = async () => {
  // 检查是否有有效的练习集ID
  if (!props.id) {
    console.warn('练习集ID无效，无法获取练习记录')
    records.value = []
    return
  }
  
  // 检查是否有有效的用户ID
  const userId = localStorage.getItem('user_id')
  if (!userId) {
    console.warn('用户ID无效，无法获取练习记录')
    records.value = []
    return
  }
  
  try {
    // 使用查询参数而不是路径参数
    const response = await http.get(`/exercises/records/`, {
      params: {
        exercise_set: props.id
      }
    })
    records.value = Array.isArray(response.data) ? response.data : []
  } catch (error) {
    console.error('获取练习记录失败:', error)
    records.value = []
  }
}

// 开始练习
const startExercise = () => {
  if (exercises.value.length === 0) {
    ElMessage.warning('该练习集没有题目，无法开始练习')
    return
  }
  
  isExercising.value = true
  currentQuestionIndex.value = 0
  userAnswer.value = getUserAnswerForCurrentQuestion()
  showAnswer.value = false
  
  // 自动开始计时器
  startTimer()
  
  // 记录开始练习的时间
  if (!progress.value || !progress.value.started_at) {
    createOrUpdateProgress()
  }
}

// 从指定题目开始练习
const startExerciseAt = (index) => {
  isExercising.value = true
  currentQuestionIndex.value = index
  userAnswer.value = ''
  showAnswer.value = false
}

// 提交答案
const submitAnswer = async () => {
  if (!userAnswer.value.trim()) {
    ElMessage.warning('请输入答案')
    return
  }
  
  try {
    // 判断答案是否正确
    const isCorrect = userAnswer.value.trim() === currentQuestion.value.answer.trim()
    const status = isCorrect ? 'correct' : 'incorrect'
    
    // 记录答案
    await http.post(`/exercises/records/`, {
      exercise: currentQuestion.value.id,
      user_answer: userAnswer.value,
      status: status
    })
    
    ElMessage.success('提交成功')
    await fetchProgress()
    await fetchRecords()
    
    if (currentQuestionIndex.value < exercises.value.length - 1) {
      nextQuestion()
    } else {
      isExercising.value = false
      ElMessage.success('练习完成！')
    }
  } catch (error) {
    console.error('提交答案失败:', error)
    ElMessage.error('提交答案失败')
  }
}

// 重置进度
const resetProgress = async () => {
  try {
    // Here you would typically send a request to reset progress
    // await http.post(`/api/exercises/${props.id}/reset-progress`)
    ElMessage.success('练习进度已重置')
    // Refresh progress data
    fetchProgress()
  } catch (error) {
    ElMessage.error('重置进度失败')
    console.error(error)
  }
}

// 标记题目
const markQuestion = () => {
  if (!currentQuestion.value) return
  const questionId = currentQuestion.value.id
  if (markedQuestions.value.has(questionId)) {
    markedQuestions.value.delete(questionId)
  } else {
    markedQuestions.value.add(questionId)
  }
}

// 检查题目是否被标记
const isMarked = (question) => {
  return question && markedQuestions.value.has(question.id)
}

// 获取当前题目
const currentQuestion = computed(() => {
  if (!exercises.value || exercises.value.length === 0) {
    return {}
  }
  
  if (currentQuestionIndex.value < 0 || currentQuestionIndex.value >= exercises.value.length) {
    currentQuestionIndex.value = 0
  }
  
  return exercises.value[currentQuestionIndex.value] || {}
})

// 获取题目的练习记录
const getRecord = (questionId) => {
  return records.value.find(r => r.exercise === questionId)
}

// 获取记录状态类型
const getRecordStatusType = (record) => {
  if (!record) return 'info'
  switch (record.status) {
    case 'correct':
      return 'success'
    case 'incorrect':
      return 'danger'
    case 'skipped':
      return 'warning'
    default:
      return 'info'
  }
}

// 获取记录状态文本
const getRecordStatusText = (record) => {
  if (!record) return '未练习'
  switch (record.status) {
    case 'correct':
      return '正确'
    case 'incorrect':
      return '错误'
    case 'skipped':
      return '跳过'
    default:
      return '未练习'
  }
}

// 获取题目类型标签
const getQuestionTypeTag = (type) => {
  const types = {
    'single_choice': 'success',
    'multiple_choice': 'warning',
    'true_false': 'info',
    'fill_blank': 'primary',
    'essay': 'danger'
  }
  return types[type] || 'info'
}

// 获取难度标签
const getDifficultyTag = (difficulty) => {
  const difficulties = {
    'easy': 'success',
    'medium': 'warning',
    'hard': 'danger'
  }
  return difficulties[difficulty] || 'info'
}

// 获取难度文本
const getDifficultyText = (difficulty) => {
  const difficulties = {
    'easy': '简单',
    'medium': '中等',
    'hard': '困难'
  }
  return difficulties[difficulty] || '未知'
}

// 获取进度状态
const getProgressStatus = (progress) => {
  if (!progress) return ''
  if (progress.is_completed) return 'success'
  if (progress.progress_percentage > 0) return 'warning'
  return 'info'
}

// 计算正确率
const calculateAccuracy = (progress) => {
  if (!progress || progress.completed_count === 0) return 0
  return Math.round((progress.correct_count / progress.completed_count) * 100)
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 导航方法
const goBack = () => {
  router.push('/exercises')
}

const prevQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
    userAnswer.value = getUserAnswerForCurrentQuestion()
  }
}

const nextQuestion = () => {
  if (currentQuestionIndex.value < exercises.value.length - 1) {
    currentQuestionIndex.value++
    userAnswer.value = ''
    showAnswer.value = false
  }
}

const goToQuestion = (index) => {
  currentQuestionIndex.value = index
  userAnswer.value = ''
  showAnswer.value = false
}

// 获取已回答的题目索引
const getAnsweredQuestionIndices = () => {
  return exercises.value
    .map((exercise, index) => ({ exercise, index }))
    .filter(item => records.value.some(r => r.exercise === item.exercise.id))
    .map(item => item.index)
}

// 获取已标记的题目索引
const getMarkedQuestionIndices = () => {
  return Array.from(markedQuestions.value)
    .map(id => exercises.value.findIndex(ex => ex.id === id))
    .filter(index => index !== -1)
}

// 监听路由参数变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    fetchExerciseSet()
  }
})

// 在组件挂载时获取数据
onMounted(() => {
  fetchExerciseSet().then(() => {
    // 检查URL中是否有mode=practice参数，如果有则自动开始练习
    if (route.query.mode === 'practice' && exercises.value.length > 0) {
      console.log('自动开始练习模式')
      isExercising.value = true
    }
  })
})

// 完成练习
const finishExercise = () => {
  ElMessageBox.confirm(
    '确定要结束本次练习吗？您的进度将被保存。',
    '完成练习',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      pauseTimer()
      isExercising.value = false
      ElMessage.success({
        message: `练习已完成！您的用时：${formatTime(elapsedTime.value)}`,
        duration: 5000
      })
    })
    .catch(() => {
      // 用户取消操作
    })
}

// 开始计时器
const startTimer = () => {
  if (!isTimerRunning.value) {
    isTimerRunning.value = true
    timerInterval.value = setInterval(() => {
      elapsedTime.value++
    }, 1000)
  }
}

// 暂停计时器
const pauseTimer = () => {
  if (isTimerRunning.value) {
    isTimerRunning.value = false
    clearInterval(timerInterval.value)
  }
}

// 重置计时器
const resetTimer = () => {
  pauseTimer()
  elapsedTime.value = 0
  ElMessage.info('计时器已重置')
}

// 格式化时间
const formatTime = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const remainingSeconds = seconds % 60
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 处理过滤变化
const handleFilterChange = (filter) => {
  activeFilter.value = filter
  applyQuestionFilter()
}

// 应用题目过滤
const applyQuestionFilter = () => {
  const answeredIndices = getAnsweredQuestionIndices()
  const markedIndices = getMarkedQuestionIndices()
  
  if (activeFilter.value === 'all') {
    filteredQuestions.value = [...Array(exercises.value.length).keys()]
  } else if (activeFilter.value === 'answered') {
    filteredQuestions.value = answeredIndices
  } else if (activeFilter.value === 'marked') {
    filteredQuestions.value = markedIndices
  } else if (activeFilter.value === 'unanswered') {
    filteredQuestions.value = [...Array(exercises.value.length).keys()].filter(
      index => !answeredIndices.includes(index)
    )
  }
}

// 在组件卸载时清除计时器
onUnmounted(() => {
  if (timerInterval.value) {
    clearInterval(timerInterval.value)
  }
})

// Handler functions for ExercisePractice
const handleSubmitAnswer = async (data) => {
  try {
    // Here you would typically send the answer to the server
    console.log('Submitted answer:', data)
    // Example API call:
    // await http.post(`/api/exercises/${props.id}/answers`, data)
  } catch (error) {
    ElMessage.error('提交答案失败')
    console.error(error)
  }
}

const handleFinishPractice = (results) => {
  isExercising.value = false
  ElMessage.success(`练习完成！得分: ${results.score}%`)
  // Here you would typically update the progress
  console.log('Practice finished with results:', results)
  // Refresh progress data
  fetchProgress()
}

const handleUpdateProgress = (progressData) => {
  console.log('Progress updated:', progressData)
  // Update local progress data if needed
}

// Handler functions for ExerciseQuestionList
const handleSelectQuestion = (questionId) => {
  selectedQuestionId.value = questionId
  console.log('Selected question:', questionId)
}

const handleStartPractice = (questionId) => {
  selectedQuestionId.value = questionId
  isExercising.value = true
  console.log('Starting practice from question:', questionId)
}
</script>

<style scoped>
.exercise-detail {
  padding: 20px;
  min-height: 100vh;
  color: var(--el-text-color-primary);
}

.exercise-card {
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-left h2 {
  margin: 0;
}

.visibility-tag {
  margin-left: 8px;
}

/* 练习集概览 */
.exercise-overview {
  margin-bottom: 24px;
}

.info-card, .nav-card, .question-card {
  background: rgba(255, 255, 255, 0.03);
  border-radius: 8px;
  padding: 16px;
  height: 100%;
  border: 1px solid rgba(255, 255, 255, 0.05);
  transition: all 0.3s ease;
}

.info-card:hover, .nav-card:hover, .question-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.info-card h3, .nav-card h3, .question-card h3 {
  margin-top: 0;
  margin-bottom: 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  padding-bottom: 8px;
  font-size: 18px;
}

.info-content p {
  margin: 8px 0;
  line-height: 1.6;
}

.main-progress {
  margin-bottom: 16px;
}

.progress-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.progress-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

/* 练习模式 */
.exercise-mode {
  margin-bottom: 24px;
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.nav-header h3 {
  margin: 0;
}

.question-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.question-button {
  width: 36px;
  height: 36px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.question-info {
  display: flex;
  gap: 8px;
}

.question-content {
  background: rgba(255, 255, 255, 0.02);
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  border: 1px solid rgba(255, 255, 255, 0.03);
}

.content-text {
  white-space: pre-wrap;
  line-height: 1.6;
}

.answer-section {
  margin-bottom: 16px;
}

.answer-actions {
  display: flex;
  gap: 8px;
  margin-top: 16px;
}

.reference-answer, .explanation {
  padding: 12px 0;
}

.answer-content, .explanation-content {
  white-space: pre-wrap;
  line-height: 1.6;
  color: var(--el-text-color-regular);
}

.explanation h4 {
  margin-top: 16px;
  margin-bottom: 8px;
  font-size: 16px;
}

.navigation-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 16px;
}

/* 题目列表 */
.questions-list {
  margin-top: 24px;
}

.questions-list h3 {
  margin-bottom: 16px;
  font-size: 18px;
}

.question-content-preview {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 500px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .exercise-overview .el-col {
    width: 100%;
    margin-bottom: 16px;
  }
  
  .exercise-mode .el-col {
    width: 100%;
  }
  
  .nav-card {
    margin-bottom: 16px;
  }
  
  .progress-stats {
    flex-wrap: wrap;
  }
  
  .stat-item {
    width: 50%;
    margin-bottom: 12px;
  }
}
</style> 